package com.ocom.payconfig.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.entity.card.EntityXfMerchantInfo;
import com.ocom.common.entity.card.EntityXfRecord;
import com.ocom.common.entity.payconfig.EntityXfMerchMoneyDay;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.exposeapi.boczhxy.AuthenticationRequest;
import com.ocom.common.request.payconfig.ConsMerchPayReportsRequest;
import com.ocom.common.request.payconfig.MerchNoRequest;
import com.ocom.common.request.payconfig.setConsMerchPayReportsRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ObjectList;
import com.ocom.common.utils.ResultUtil;
import com.ocom.payconfig.client.XfRecordFeign;
import com.ocom.payconfig.service.XfMerchMoneyDayService;
import com.ocom.payconfig.service.XfMerchantInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@RestController
public class ConsMerchPayController {

    @Autowired
    private XfMerchantInfoService xfMerchantInfoService;

    @Autowired
    private XfMerchMoneyDayService xfMerchMoneyDayService;

    @Autowired
    private XfRecordFeign xfRecordFeign;


    @PostMapping(PayConfigUrl.Url_getConsMerchPayList)
    public Result getConsMerchPayList(@RequestParam("comId") Long comId) {

        List<EntityXfMerchantInfo> merchList = xfMerchantInfoService.GetMerchInfo(comId);

        List<EntityXfMerchantInfo> data = merchList.stream()
                .filter(merch -> merch.getMerchNo() != null && !merch.getMerchNo().isEmpty())
                .collect(Collectors.toList());

        ArrayList<EntityXfMerchantInfo> list = new ArrayList<>();
        ArrayList<EntityXfMerchantInfo> merchList2 = new ArrayList<>();
        for (EntityXfMerchantInfo entityXfMerchantInfo : data) {
            entityXfMerchantInfo.getMerchIds().add(String.valueOf(entityXfMerchantInfo.getMerchId()));
            for (EntityXfMerchantInfo xfMerchantInfo : merchList) {
                if (!Objects.equals(xfMerchantInfo.getParentMerchId(), entityXfMerchantInfo.getMerchId())) {
                    continue;
                }
                merchList2.add(xfMerchantInfo);
            }
            for (EntityXfMerchantInfo xfMerchantInfo : merchList2) {
                if (ObjectUtil.isNotEmpty(xfMerchantInfo.getMerchNo())) {
                    continue;
                }
                entityXfMerchantInfo.getMerchIds().add(String.valueOf(xfMerchantInfo.getMerchId()));
            }
            list.add(entityXfMerchantInfo);

        }
        List<MerchNoRequest> merchNoList = ObjectList.copyList(list, MerchNoRequest::new);
        return ResultUtil.success(merchNoList);

    }

    /**
     * 生成商户每日转账单
     *
     * @param request
     * @return
     * @throws ParseException
     */
    @PostMapping(PayConfigUrl.Url_setConsMerchPayReports)
    public Result setConsMerchPayReports(@RequestBody setConsMerchPayReportsRequest request) throws ParseException {

        String payDate = request.getPayDate();
        LocalDate date = LocalDate.parse(payDate);
        LocalDate currentDate = LocalDate.now();
        if (date.isAfter(currentDate) || date.isEqual(currentDate)) {
            return ResultUtil.success(ResultEnum.Err_4202);
        }

        List<EntityXfMerchMoneyDay> list = xfMerchMoneyDayService.getXfMerchMoneyDayByPayDate2(Long.valueOf(request.getComId()), payDate);
        if (ObjectUtil.isNotEmpty(list)) {
            return ResultUtil.success(list);
        }
        List<EntityXfMerchMoneyDay> list3 = xfMerchMoneyDayService.getXfMerchMoneyDayByPayDate(Long.valueOf(request.getComId()), payDate);
        if (ObjectUtil.isNotEmpty(list3)) {
            return ResultUtil.success();
        }
        if (ObjectUtil.isEmpty(request.getMerchNoList())) return ResultUtil.success();

        JSONArray jsonArray = null;

        Result result = xfRecordFeign.getPayDate(Long.valueOf(request.getComId()), payDate);

        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result.getData()));

        jsonArray = jsonObject.getJSONArray("list");

//        ArrayList<EntityXfRecord> payDateInfo = new ArrayList<>();

        //查询前一天是否有欠费记录
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        LocalDate sourceDate = LocalDate.parse(payDate, formatter);
//        LocalDate targetDate = sourceDate.minusDays(1);
//        String format = targetDate.format(formatter);
//        List<EntityXfMerchMoneyDay> merchMoneyDayList = xfMerchMoneyDayService.recordOfArrears(Long.valueOf(request.getComId()), format);

        //汇总
        for (MerchNoRequest merchNoList : request.getMerchNoList()) {
            String merchNo = merchNoList.getMerchNo();
            String merchName = merchNoList.getMerchName();
            Integer payAmount = 0;
            Integer manageAmount = 0;
            Integer nowReceived = 0;
            String remark = "";
            String repairPayDate = "";

            for (String merchId : merchNoList.getMerchIds()) {
                for (Object object : jsonArray) {
                    String jsonString = JSON.toJSONString(object);
                    EntityXfRecord entityXfRecord = JSON.parseObject(jsonString, EntityXfRecord.class);
                    if (!merchId.equals(String.valueOf(entityXfRecord.getMerchId()))) {
                        continue;
                    }

                    payAmount = Math.toIntExact(entityXfRecord.getPayAmount());
                    remark = entityXfRecord.getMerchName() == null ? "" : entityXfRecord.getMerchName();
                    remark += remark + '(' + entityXfRecord.getPayAmount() * 0.01 + ')';

                    nowReceived = payAmount - manageAmount;

                    EntityXfMerchMoneyDay xfMerchMoneyDay = new EntityXfMerchMoneyDay();
                    xfMerchMoneyDay.setMerchNo(merchNo);
                    xfMerchMoneyDay.setComId(Integer.valueOf(request.getComId()));
                    xfMerchMoneyDay.setMerchName(merchName);
                    xfMerchMoneyDay.setPayDate(new SimpleDateFormat("yyyy-MM-dd").parse(payDate));
                    xfMerchMoneyDay.setPayAmount(payAmount);
                    xfMerchMoneyDay.setTraceNo(request.getTraceNo());
                    xfMerchMoneyDay.setManageAmount(manageAmount);
                    xfMerchMoneyDay.setNowReceived(nowReceived);
                    xfMerchMoneyDay.setRemark(remark);
                    xfMerchMoneyDay.setMerchNoOut(merchNoList.getMerchNoOut());
                    xfMerchMoneyDay.setRepairPayDate(repairPayDate);
                    xfMerchMoneyDay.setCreateTime(new Date());
                    xfMerchMoneyDayService.saveXfMerchMoneyDay(Long.valueOf(request.getComId()), xfMerchMoneyDay);
                }
            }
        }
        List<EntityXfMerchMoneyDay> xfMerchMoneyDay = xfMerchMoneyDayService.getXfMerchMoneyDayByPayDate2(Long.valueOf(request.getComId()), payDate);
        return ResultUtil.success(xfMerchMoneyDay);
    }

    @PostMapping(PayConfigUrl.Url_getConsMerchPayReports)
    public Result getConsMerchPayReports(@RequestBody ConsMerchPayReportsRequest request) {
        return xfMerchMoneyDayService.getMerchMoneyDayList(Long.valueOf(request.getComId()), request);

    }

    @PostMapping(PayConfigUrl.Url_updateConsMerchPayReports)
    public Result updateConsMerchPayReports(@RequestBody AuthenticationRequest request) {
        return xfMerchMoneyDayService.modifyMerchMoneyDay(Long.valueOf(request.getComId()),request);
    }
}